/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2024-11-20 16:53:46
 * @LastEditors: 程前
 * @LastEditTime: 2024-12-30 09:47:32
 */

type TreeSelectItem = {
  key: string | number;
  label: string;
  disabled?: boolean;
  isLeaf?: boolean;
  children?: TreeSelectItem[];
};

type TreeConvertOptions = {
  /**
   * KEY字段（ID字段）
   */
  keyField: string;

  /**
   * 值字段
   */
  valueField: string;

  /**
   * 上级KEY字段（上级ID字段）
   */
  parentKeyField: string | number;

  /**
   * 标题名称字段
   */
  labelField: string;

  /**
   * 根节点KEY值 (根节点ID值)
   */
  rootKey: string | number | null;
};

/**
 *  创建树型下拉组件数据源
 * @param list 原始数据列表
 * @param options  转换参数
 * @param parentKey 上级节点 KEY 值
 */
export const createTreeSelectList = function (
  list: Array<any>,
  options: TreeConvertOptions,
  parentKey?: string | number,
): TreeSelectItem[] {
  let trees: TreeSelectItem[] = [];

  let { keyField, parentKeyField, labelField, rootKey } = options;
  let pid = parentKey || parentKey === '' ? parentKey : rootKey;
  /**
   * 检索当前层级数据
   */
  let items = list.filter((x: any) => {
    return x[parentKeyField] === pid;
  });

  //生成当前层级列表
  items.map((x: any) => {
    let item: TreeSelectItem = {
      key: x[keyField],
      label: x[labelField],
      // disabled: x.disabled,
      // isLeaf: x.isLeaf,
    };
    let children = createTreeSelectList(list, options, x[keyField]);
    if (children && children.length) {
      item.children = children;
    }
    trees.push(item);
  });
  return trees;
};
